package com.taylor.community.service;

import com.github.benmanes.caffeine.cache.CacheLoader;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.LoadingCache;
import com.taylor.community.dao.DiscussPostMapper;
import com.taylor.community.entity.DiscussPost;
import com.taylor.community.util.RedisKeyUtil;
import com.taylor.community.util.SensitiveFilter;

import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.util.HtmlUtils;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class DiscussPostService {
    private static final Logger logger = LoggerFactory.getLogger(DiscussPostService.class);
    @Autowired
    private DiscussPostMapper discussPostMapper;
    @Autowired
    private SensitiveFilter sensitiveFilter;
    @Value("${caffeine.posts.max-size}")
    private int maxSize;
    @Value("${caffeine.posts.expire-seconds}")
    private int expireSeconds;
    //caffeine核心接口：分别有做同步阻塞等待和异步请求的，这里使用同步的LoadingCache
    //帖子列表的缓存
    private LoadingCache<String,List<DiscussPost>> postListCache;
    //帖子总数的缓存
    private LoadingCache<Integer,Integer> postRowsCache;

    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 缓存的参数初始化一次即可，但是每次postListCache.get时都会先看缓存中有没有数据，没有则执行build里面的逻辑从数据库加载到缓存
     */
    @PostConstruct
    public void init(){
        //初始化帖子列表的缓存
        postListCache = Caffeine.newBuilder()
                .maximumSize(maxSize)
                .expireAfterWrite(expireSeconds, TimeUnit.SECONDS)
                .build(new CacheLoader<String, List<DiscussPost>>() {
                    @Nullable
                    @Override
                    public List<DiscussPost> load(@NonNull String key) throws Exception {
                        if (key == null || key.length()== 0){
                            throw new IllegalArgumentException("参数错误!");
                        }
                        String [] params = key.split(":");
                        if (params == null || params.length != 2){
                            throw new IllegalArgumentException("参数错误!");
                        }
                        int offset = Integer.valueOf(params[0]);
                        int limit = Integer.valueOf(params[1]);
                        //先从Redis中查
                        List<DiscussPost> redisCacheList = redisTemplate.opsForList().range(RedisKeyUtil.getHotpost(offset,limit),0,-1);
                        //redis比caffeine早一分钟过期，保证一级缓存未命中时，二级缓存也未命中，更新相对及时
                        redisTemplate.expire(RedisKeyUtil.getHotpost(offset,limit),9,TimeUnit.MINUTES);
                        if(redisCacheList.size() != 0){
                            return redisCacheList;
                        }
                        logger.debug("load post list from DB.");
                        redisCacheList = discussPostMapper.selectDiscussPosts(0,offset,limit,1);
                        //redis里面也要存一份，做二级缓存
                        redisTemplate.opsForList().leftPush(RedisKeyUtil.getHotpost(offset,limit),redisCacheList);
                        return redisCacheList;
                    }
                });
        //初始化帖子总数的缓存
        postRowsCache = Caffeine.newBuilder()
                //其实1个就够了
                .maximumSize(maxSize)
                .expireAfterWrite(expireSeconds, TimeUnit.SECONDS)
                .build(new CacheLoader<Integer, Integer>() {
                    @Nullable
                    @Override
                    public Integer load(@NonNull Integer key) throws Exception {
                        Integer rows = (Integer)redisTemplate.opsForValue().get(RedisKeyUtil.PREFIX_TOTALPOST);
                        if(rows!=null){
                            return rows;
                        }
                        logger.debug("load post rows from DB.");
                        rows = discussPostMapper.selectDiscussPostRows(key);
                        //redis比caffeine早一分钟过期，保证一级缓存未命中时，二级缓存也未命中，更新相对及时
                        redisTemplate.opsForValue().set(RedisKeyUtil.PREFIX_TOTALPOST,rows,9,TimeUnit.MINUTES);
                        return rows;
                    }
                });
    }
    /**
     *
     * @param userId
     * @param offset
     * @param limit
     * @param orderMode 0:按类型倒序-按时间倒序 1:按类型倒序-按分数倒序-按时间倒序
     * @return
     */
    public List<DiscussPost> findDiscussPosts(int userId, int offset, int limit,int orderMode){
        //只缓存首页的帖子 此时userId为0，orderMode为1
        if (userId == 0 && orderMode == 1){
            return postListCache.get(offset + ":" + limit);
        }
        logger.debug("load post list from DB.");
        return discussPostMapper.selectDiscussPosts(userId,offset,limit,orderMode);
    }
    public int findDiscussPostRows(int userId){
        //userId为0时才是从首页查帖子总行数
        if (userId == 0){
            //以userId为key 永远是0 问题不大
            return postRowsCache.get(userId);
        }
        logger.debug("load post rows from DB.");
        return discussPostMapper.selectDiscussPostRows(userId);
    }
    public int addDiscussPost(DiscussPost discussPost){
        if(discussPost == null){
            throw new IllegalArgumentException("参数不能为空");
        }
        //转义HTML标记 避免被识别成html标签
        discussPost.setTitle(HtmlUtils.htmlEscape(discussPost.getTitle()));
        discussPost.setContent(HtmlUtils.htmlEscape(discussPost.getContent()));
        //过滤敏感词
        discussPost.setTitle(sensitiveFilter.filter(discussPost.getTitle()));
        discussPost.setContent(sensitiveFilter.filter(discussPost.getContent()));
        return discussPostMapper.insertDiscussPost(discussPost);
    }
    public DiscussPost findDiscussPostById(int id){
        return discussPostMapper.selectDiscussPostById(id);
    }
    public int updateCommentCount(int id,int commentCount){
        return discussPostMapper.updateCommentCount(id,commentCount);
    }
    public int updateStatus(int id,int status){
        return discussPostMapper.updateStatus(id, status);
    }
    public int updateType(int id,int type){
        return discussPostMapper.updateType(id, type);
    }
    public int updateScore(int id,double score){
        return discussPostMapper.updateScore(id, score);
    }
}
